package cn.wind.xboot.core.utils;

import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;

import java.lang.reflect.InvocationTargetException;

/**
 * @author xukk
 * @date 2018/5/4.
 */
public class UserUtil {
    public static String principal() {
        SecurityContext ctx = SecurityContextHolder.getContext();
        if (ctx == null) {
            return "0";
        }
        if (ctx.getAuthentication() == null) {
            return "0";
        }
        if (ctx.getAuthentication().getPrincipal() == null) {
            return "0";
        }
        try {
            Object object=ctx.getAuthentication().getPrincipal();
            if(object instanceof String){
                return "0";
            }
            String userType=BeanUtil.getProperty(object,"userType");
            String userId=BeanUtil.getProperty(object,"userId");
            return userType+":"+userId;
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        }
        return "0";
    }
    public static Long currentUserId() {
        SecurityContext ctx = SecurityContextHolder.getContext();
        if (ctx == null) {
            return 0L;
        }
        if (ctx.getAuthentication() == null) {
            return 0L;
        }
        if (ctx.getAuthentication().getPrincipal() == null) {
            return 0L;
        }
        try {
            Object object=ctx.getAuthentication().getPrincipal();
            if(object instanceof String){
                return 0L;
            }
            return Long.valueOf(BeanUtil.getProperty(ctx.getAuthentication().getPrincipal(),"userId"));
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        }
        return 0L;
    }
}
